/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package InterfaceCliente;

import java.awt.Color;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import pbl_cliente.*;

/**
 *
 * @author tayane
 */
public class TelaPrincipal extends javax.swing.JFrame {

    /**
     * Creates new form Login
     */
    private String DadosServidor;
    private PBL_cliente cli;
    List<String> usuariosON;
    private Socket cliente;
    private TelaNovoCompromisso tc;
    private List<String> listaUsersCad;
    private TelaVisualizaCompromisso vc;
    private List<String> listaComp;
    private List<String> listaConexoesAtivas;
    
    // Cria um novo DefaultListModel  
    DefaultListModel listaCompromissos = new DefaultListModel(); //lista para armazenar os compromissos
    DefaultListModel listaUsuariosON = new DefaultListModel(); //lista para armazenar os usuarios online

    // Cria um novo DefaultListModel  
    public TelaPrincipal() {

        initComponents();
        setVisible(true);

    }

    public TelaPrincipal(Socket clt, PBL_cliente cl, List<String> listaCompromissos, List<String> conexoesAtivas) {

        initComponents();
        setVisible(true);
        labelCompromissos.setForeground(Color.MAGENTA);
        labelUsuariosOnline.setForeground(Color.blue);
        this.cliente = clt;
        this.cli = cl;
        listaUsersCad = new ArrayList<String>();
        this.listaComp = new ArrayList<String>();
        this.listaConexoesAtivas = conexoesAtivas;
        //this.conexao = conexao;
        setLocationRelativeTo(null);
    }

    public void setListaComp(List<String> listaComp) {
        this.listaComp = listaComp;
    }

    public void setCompromissoNaTela(String NewCompromisso) {

        //this.listaComp = listaDeCompromissos;
        listaComp.add(NewCompromisso);
        //for (int i = 0; i < listaDeCompromissos.size(); i++){
        //String[] dadosDividos = listaDeCompromissos.get(i).split(":");
        String[] dadosDividos = NewCompromisso.split(":");
        listaCompromissos.addElement(dadosDividos[1] + " | " + dadosDividos[2] + " - " + dadosDividos[3] + " | " + dadosDividos[5]);
        this.exibeListaCompromissos.setModel(listaCompromissos);
        // }

    }

    public void setListaCompromissosNaTela(List<String> listaDeCompromissos) {
        //  System.out.println("entrei no método setListaCompromissosNaTela");
        this.listaComp = listaDeCompromissos;
        for (int i = 0; i < listaDeCompromissos.size(); i++) {

            String[] dadosDividos = listaDeCompromissos.get(i).split(":");
            System.out.println(dadosDividos[4]);
            listaCompromissos.addElement(dadosDividos[1] + " | " + dadosDividos[2] + " - " + dadosDividos[3] + " | " + dadosDividos[5]);
            this.exibeListaCompromissos.setModel(listaCompromissos);
        }

    }

    /*public void setCorCompromissos(){
    
    for (int k = 0; k < listaComp.size(); k++){
    
    String dadosCompromisso = listaComp.get(k); 
    String convidados = dadosCompromisso.split(":")[10];
    String [] convidadosDivididos = convidados.split("#");
    //System.out.println("quantidade de convidados: " + convidadosDivididos.length);
    
    for (int i = 0; i < convidadosDivididos.length; i++){               
    String email = convidadosDivididos[i].split(" - ")[1];            
    System.out.println("email do convidado: " + email);
    if (email.equals(this.cli.getEmailUsuarioConectado())){
    //System.out.println("Fui convidado!");
    
    }
    }
    
    }  
    }*/
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSeparator2 = new javax.swing.JSeparator();
        jFrame1 = new javax.swing.JFrame();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        NomeAgendaEletronica = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        NovoCompromisso = new javax.swing.JButton();
        MeusCompromissos = new javax.swing.JButton();
        Sair = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JSeparator();
        labelCompromissos = new javax.swing.JLabel();
        labelUsuariosOnline = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        exibeListaCompromissos = new javax.swing.JList();
        jScrollPane3 = new javax.swing.JScrollPane();
        exibeListaUsuariosON = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        iniciaChat = new javax.swing.JButton();

        javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
        jFrame1.getContentPane().setLayout(jFrame1Layout);
        jFrame1Layout.setHorizontalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jFrame1Layout.setVerticalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jLabel3.setFont(new java.awt.Font("Ubuntu", 1, 13)); // NOI18N
        jLabel3.setText("Compromissos do Dia");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBackground(java.awt.Color.white);

        NomeAgendaEletronica.setFont(new java.awt.Font("Ubuntu", 1, 18)); // NOI18N
        NomeAgendaEletronica.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        NomeAgendaEletronica.setText("Agenda Eletrônica");

        NovoCompromisso.setIcon(new javax.swing.ImageIcon(getClass().getResource("/InterfaceCliente/6098_32x32.png"))); // NOI18N
        NovoCompromisso.setText("Novo Compromisso");
        NovoCompromisso.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NovoCompromissoActionPerformed(evt);
            }
        });

        MeusCompromissos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/InterfaceCliente/6231_32x32.png"))); // NOI18N
        MeusCompromissos.setText("Meus Compromissos");
        MeusCompromissos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MeusCompromissosActionPerformed(evt);
            }
        });

        Sair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/InterfaceCliente/sair.png"))); // NOI18N
        Sair.setText("Sair");
        Sair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SairActionPerformed(evt);
            }
        });

        labelCompromissos.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        labelCompromissos.setText("Compromissos");

        labelUsuariosOnline.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        labelUsuariosOnline.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        labelUsuariosOnline.setText("Usuários Online");
        labelUsuariosOnline.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        exibeListaCompromissos.setFont(new java.awt.Font("Arial", 1, 13)); // NOI18N
        exibeListaCompromissos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                exibeListaCompromissosMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(exibeListaCompromissos);

        exibeListaUsuariosON.setFont(new java.awt.Font("Arial", 1, 13)); // NOI18N
        jScrollPane3.setViewportView(exibeListaUsuariosON);

        jLabel1.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        jLabel1.setText("* Para visualizar os detalhes de um compromisso, dê dois cliques sobre o mesmo.");

        jLabel2.setText("Data");

        jLabel4.setText("Horário");

        jLabel5.setText("Assunto");

        iniciaChat.setText("Chat");
        iniciaChat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                iniciaChatActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 705, Short.MAX_VALUE)
            .addComponent(jSeparator3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 705, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(277, Short.MAX_VALUE)
                .addComponent(NomeAgendaEletronica)
                .addGap(268, 268, 268))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(25, 25, 25)
                        .addComponent(NovoCompromisso)
                        .addGap(43, 43, 43)
                        .addComponent(MeusCompromissos)
                        .addGap(41, 41, 41)
                        .addComponent(Sair)
                        .addGap(42, 42, 42)
                        .addComponent(iniciaChat, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 461, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel2)
                        .addGap(40, 40, 40)
                        .addComponent(jLabel4)
                        .addGap(89, 89, 89)
                        .addComponent(jLabel5)))
                .addContainerGap(34, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(187, 187, 187)
                .addComponent(labelCompromissos)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 245, Short.MAX_VALUE)
                .addComponent(labelUsuariosOnline)
                .addGap(57, 57, 57))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(NomeAgendaEletronica)
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(NovoCompromisso)
                    .addComponent(MeusCompromissos, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Sair)
                    .addComponent(iniciaChat))
                .addGap(18, 18, 18)
                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addGap(7, 7, 7)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelUsuariosOnline)
                    .addComponent(labelCompromissos))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 344, Short.MAX_VALUE)
                    .addComponent(jScrollPane2))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void MeusCompromissosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MeusCompromissosActionPerformed
        // TODO add your handling code here:
        //cli.usuarioConsultando();
    }//GEN-LAST:event_MeusCompromissosActionPerformed

    private void NovoCompromissoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NovoCompromissoActionPerformed
        // TODO add your handling code here:
        //TelaNovoCompromisso novoCompromisso = new TelaNovoCompromisso(cliente, cli);
        tc = new TelaNovoCompromisso(cliente, cli, usuariosON);
        tc.setUsuariosCadastrados(listaUsersCad);
        
        cli.usuarioCriandoCompromisso();
    }//GEN-LAST:event_NovoCompromissoActionPerformed

    public synchronized void setUsuarios(List<String> listaUsuariosON) {
        usuariosON = new ArrayList<String>(listaUsuariosON);
        exibeListaUsuariosON.setListData(listaUsuariosON.toArray());

    }

    public void setUsuariosCadastrados(List<String> listaUsuariosCadastrados) {
        listaUsersCad = new ArrayList<String>(listaUsuariosCadastrados);
    }

private void SairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SairActionPerformed
    System.exit(0);
}//GEN-LAST:event_SairActionPerformed

    private void exibeListaCompromissosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exibeListaCompromissosMouseClicked
        // TODO add your handling code here:
        int count = evt.getClickCount();
        if (count > 1) {

            String compromissoSelecionado = (String) exibeListaCompromissos.getSelectedValue();
            System.out.println(compromissoSelecionado);
            //System.out.println(exibeListaCompromissos.getSelectedIndex());
            System.out.println("DADOS DO COMPROMISSO SELECIONADO: " + listaComp.get(exibeListaCompromissos.getSelectedIndex()));
            String[] dadosDoComp = listaComp.get(exibeListaCompromissos.getSelectedIndex()).split(":");
            vc = new TelaVisualizaCompromisso(this.cli, listaComp.get(exibeListaCompromissos.getSelectedIndex()));
            //vc = new TelaVisualizaCompromisso();
            //System.out.println(dadosDoComp[1]);
            vc.setDataCompromisso(dadosDoComp[1]);
            vc.setHoraInicio(dadosDoComp[2]);
            vc.setHoraFim(dadosDoComp[3]);
            vc.setCriadorCompromisso(dadosDoComp[4]);
            vc.setTituloCompromisso(dadosDoComp[5]);
            vc.setLocalCompromisso(dadosDoComp[6]);
            vc.setDescricaoCompromisso(dadosDoComp[7]);

            System.out.println("convidados: " + dadosDoComp[10]);
            String[] convidadosDivididos = dadosDoComp[10].split("#");
            //System.out.println("tamanho convidados divididos" + convidadosDivididos.length);
            for (int i = 0; i < convidadosDivididos.length; i++) {
                vc.setListaConvidadosNaTela(convidadosDivididos[i]);
            }
            System.out.println("confirmados: " + dadosDoComp[11]);
            if (!dadosDoComp[11].equals("null")) {
                System.out.println("vou exibir os que confirmaram");
                String[] confirmadosDivididos = dadosDoComp[11].split("#");
                for (int i = 0; i < confirmadosDivididos.length; i++) {
                    vc.setListaConfirmadosNaTela(confirmadosDivididos[i]);
                }
            }
            System.out.println("recusaram: " + dadosDoComp[12]);
            if (!dadosDoComp[12].equals("null")) {
                System.out.println("vou exibir os que recusaram");
                String[] recusaramDivididos = dadosDoComp[12].split("#");
                for (int i = 0; i < recusaramDivididos.length; i++) {
                    vc.setListaRecusaramNaTela(recusaramDivididos[i]);
                }
            }

        }

    }//GEN-LAST:event_exibeListaCompromissosMouseClicked

    private void iniciaChatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_iniciaChatActionPerformed

        if(cli.getContChat() == 3){
            JOptionPane.showMessageDialog(rootPane, "Não existem usuários online para inciar uma conversa.");
        }
        else{
            new TelaConvidaUsuariosChat(this.listaConexoesAtivas, cli.getEmailUsuarioConectado(), cli);
        }
    }//GEN-LAST:event_iniciaChatActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new TelaPrincipal().setVisible(true);
            }
        });

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton MeusCompromissos;
    private javax.swing.JLabel NomeAgendaEletronica;
    private javax.swing.JButton NovoCompromisso;
    private javax.swing.JButton Sair;
    private javax.swing.JList exibeListaCompromissos;
    private javax.swing.JList exibeListaUsuariosON;
    private javax.swing.JButton iniciaChat;
    private javax.swing.JFrame jFrame1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel labelCompromissos;
    private javax.swing.JLabel labelUsuariosOnline;
    // End of variables declaration//GEN-END:variables
//    private List<String> lista;
//    public List<String> concatenaSinal(List<String> list){
//        lista = new ArrayList<String>();
//        if(!list.isEmpty()){
//            System.out.println("entreino if e concatenaSinal");
//        for(int j=0;j<list.size();j++){
//            //if(list.get(j).split("-")[1].isEmpty())
//            System.out.println("DDDDDDDDDDD");
//            lista.add(list.get(j).concat("-Consultando"));
//            
//            System.out.println("GGGGG: "+ lista.get(j));
//        }
//        }
//        return lista;
//    }
}
